package com.wrupple.muba.base.client.module.services.logic;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.google.gwt.activity.shared.Activity;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Widget;
import com.wrupple.muba.base.client.view.impl.DesktopSelectionGridElement;
import com.wrupple.muba.catalogs.client.widgets.impl.CatalogUserInterfaceMessages;
import com.wrupple.muba.common.client.state.IconSelectionTask.GridElement;
import com.wrupple.muba.common.domain.DesktopPlace;
import com.wrupple.muba.common.shared.StateTransition;
import com.wrupple.muba.widget.client.widgets.panels.LayoutGrid;
import com.wrupple.vegetate.domain.PersistentImageMetadata;

public class DesktopSelectionStateDelegateImpl implements
		DesktopSelectionStateDelegate {

	class SelectionHandler implements ClickHandler {
		DesktopPlace place;

		public SelectionHandler(DesktopPlace place) {
			super();
			this.place = place;
		}

		@Override
		public void onClick(ClickEvent event) {
			DesktopPlace o = new DesktopPlace(place);
			onDone.setResultAndFinish(Collections.singletonList(o));
		}

	}
	
	List<GridElement> elements;
	private StateTransition<List<DesktopPlace>> onDone;
	CatalogUserInterfaceMessages msgs ;
	
	public DesktopSelectionStateDelegateImpl() {
		super();
		msgs = GWT.create(CatalogUserInterfaceMessages.class);
	}

	@Override
	public LayoutGrid getLayoutGrid() {
		LayoutGrid appHolder = new LayoutGrid();
		appHolder.setStyleName("home-screen-container");
		elements = new ArrayList<GridElement>();
		return appHolder;
	}

	@Override
	public int getGridWidth() {
		return 550;
	}

	@Override
	public List<GridElement> getElements(List<DesktopPlace> parameter,
			StateTransition<List<DesktopPlace>> onDone) {
		this.onDone = onDone;
		return elements;
	}

	@Override
	public void init(Map<String, Activity> activityMap,
			Set<DesktopPlace> installedWebapps) {
		HasClickHandlers button = null;
		String name = null;
		String appId = null;
		String iconFileid;
		for (DesktopPlace installeditem : installedWebapps) {
			appId = installeditem.getActivity();
			name = installeditem.getProperty(DesktopPlace.LABEL_PARAMETER);
			iconFileid = installeditem.getProperty(DesktopPlace.IMAGE_PARAMETER);
			button = new Image("/vegetate/catalog/"+PersistentImageMetadata.CATALOG+"/read/"+iconFileid+"/96");
			if (name == null) {
				name = appId;
			}
		
			
			elements.add(new DesktopSelectionGridElement((Widget)button, name));
			button.addClickHandler(new SelectionHandler(installeditem));

		}
	}

}
